Lists清單 << 
Previous Next >> 心得
More Conditionals更多條件
The nice thing about conditionals is that they follow logical operations. They can also be used to test equality. Let’s do a small example. Let’s say I want to make a piece of code that converts from a numerical grade (1-100) to a letter grade (A, B, C, D, F). The code would look like this:
grade = input("Enter your grade: ")
if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 65:
  print("D")
else:
  print("F")
What happens if grade is 50? All the conditions are false, so "F" gets printed on the screen. But what if grade is 95? Then all the conditions are true and everything gets printed, right? Nope! What happens is the program goes line by line. The first condition (grade >= 90) is satisfied, so the program enters into the code inside the if statement, executing print("A"). Once code inside a conditional has been executed, the rest of the conditions are skipped and none of the other conditionals are checked.
關於條件的好處是它們遵循邏輯運算。它們也可以用於測試相等性。讓我們做一個小例子。假設我要編寫一段代碼,將其從數字等級(1-100)轉換為字母等級(A,B,C,D,F)。代碼如下所示:
grade = input("Enter your grade: ")
if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 65:
  print("D")
else:
  print("F")
如果grade是50,會發生什麼?所有條件均為假,因此"F"將其打印在屏幕上。但是,如果grade是95,該怎麼辦?然後所有條件都成立,一切都打印出來了,對吧?不!程序將逐行執行。滿足第一個條件(等級> = 90),因此程序將輸入if語句內的代碼,執行print("A")。一旦執行了條件語句中的代碼,將跳過其餘條件,並且不檢查其他條件。
Lists清單 << 
Previous Next >> 心得